'use strict';

const cheerio = require('cheerio');



exports.index = async ctx => {

  let resData = []

  for (let i = 5; i < 6; i++) {
    const url = `https://gz.fang.anjuke.com/loupan/all/${i === 0 ? '' : 'p' + (i + 1) + '_'}w1_z1/`
    console.log(url)
    const data = await ctx.curl(url, {
      timeout: 1000 * 1000,
    });
    const html = data.data.toString('utf8');
    const $ = cheerio.load(html);
    const list = $('.key-list .item-mod');

    const promiseArr = []

    list.each(async (index, element) => {
      const item = $(element)
      const title = item.find('.lp-name')
      const href = title.attr('href')

      const id = /[0-9]{6}/.exec(href)[0]

      const loupan_tab_href = `https://gz.fang.anjuke.com/loupan/canshu-${id}.html?from=loupan_tab`

      console.log('loupan_tab_href = ',loupan_tab_href)

      // https://gz.fang.anjuke.com/loupan/canshu-247649.html?from=loupan_tab



      if (index === 0) {
        promiseArr.push(new Promise(async (resolve) => {
          const data = await ctx.curl(loupan_tab_href, {
            timeout: 1000 * 1000,
          });
          const html = data.data.toString('utf8');
          const $ = cheerio.load(html);
          // const name = $('.basic-fst').text().trim();
          // const price = $('.sp-price.other-price').text().trim();
          // const openTime = $('.basic-parms dd').eq(1).find('span').text().trim();
          // const jiaofangTime = $('.basic-parms dd').eq(2).find('span').text().trim();
          // const huxingTime = $('.basic-parms dd').eq(3).find('div').text().trim();

          const list = $('.can-container .list')
          const name = list.find('li').eq(0).find('.des a').text().trim()

          resolve({
            // price,
            name,
            // openTime,
            // jiaofangTime,
            // huxingTime
          })
        }))
      }
    })

    const datas = await Promise.all(promiseArr)

    console.log(datas)

    resData = [...resData, ...datas]
  }

  ctx.sendSuccess(resData);
};
